package aes

import (
	"crypto/aes"
	"bytes"
	"crypto/cipher"
)

//加密
func CbcEncode(src,key,iv []byte) ([]byte,error) {
	block,err := aes.NewCipher(key)
	if err != nil {
		return nil,err
	}
	blockSize := block.BlockSize()

	//pkcs7填充
	srcBys := pkcs7Padding([]byte(src),blockSize)

	//加密模式
	blockMode := cipher.NewCBCEncrypter(block,iv)

	dst := make([]byte,len(srcBys))
	blockMode.CryptBlocks(dst,srcBys)
	return dst,nil
}

//解密
func CbcDecode(src,key,iv []byte) ([]byte,error) {
	block,err := aes.NewCipher(key)
	if err != nil {
		return nil,err
	}

	blockMode := cipher.NewCBCDecrypter(block,[]byte(iv))

	dst := make([]byte,len(src))
	blockMode.CryptBlocks(dst,src)

	return pkcs7Unpadding(dst),nil
}


//pkcs7填充
func pkcs7Padding(src []byte,blockSize int) []byte {
	paddingLen := blockSize - len(src) % blockSize
	padtext := bytes.Repeat([]byte{byte(paddingLen)},paddingLen)
	return append(src,padtext...)
}
//pkcs7去填充
func pkcs7Unpadding(src []byte) []byte {
	srcLen := len(src)
	paddingByte := src[srcLen-1]
	srcLen -= int(paddingByte)
	if srcLen < 0 {
		return nil
	}
	return src[:srcLen]
}

